<?php
/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2024/3/14
 * Time: 14:37
 */

namespace app\common\service;


use app\common\enum\SetWorkspacesSjqq_ztEnum;
use app\modules\setting\models\workspaces\SetWorkspacesRunningLog;
use app\modules\setting\models\workspaces\SetWorkspacesSjdl;
use app\modules\setting\models\workspaces\SetWorkspacesSjqq;
use app\modules\setting\models\workspaces\SetWorkspacesYhsp;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class TiktokDataGet
{
    public $userName="allanyao";
    public $apiKey="6ZpAJ71wzvmoZbx8Kwx9q9NlS";
    public $apiEndPoint = "http://api.scraping-bot.io/scrape/data-scraper";
    public $json;

    public function getAuth(){
        $auth = base64_encode($this->userName.":".$this->apiKey);
        return "Authorization: Basic ".$auth;
    }

    public function setJson($url){
        $postParams = [
            'scraper' => "tiktokProfile",
            'url'=>$url,
        ];
        $this ->json = json_encode($postParams);
    }
    /**
     * @param $row SetWorkspacesSjqq
     * @return bool
     * @throws \Exception
     */
    public function running($row){
        $row->zt = SetWorkspacesSjqq_ztEnum::RUNNING;
        return $row->save();
    }
    /**
     * @param $row SetWorkspacesSjqq
     * @return bool
     * @throws \Exception
     */
    public function isRunning($row){
        $key = $this->getRunningKey($row);
        $cache = \Yii::$app->cache;
        return !!$cache->get($key);
    }
    /**
     * @param $row SetWorkspacesSjqq
     * @param $run bool
     * @return bool
     * @throws \Exception
     */
    public function setRunning($row , $run){
        $run = !!$run;
        $key = $this->getRunningKey($row);
        $cache = \Yii::$app->cache;
        $cache->set($key , $run);
    }
    /**
     * @param $row SetWorkspacesSjqq
     * @return string
     * @throws \Exception
     */
    public function getRunningKey($row){
        return "TiktokDataGetRunning2{$row->id}";
    }
    /**
     * @param $row SetWorkspacesSjqq
     * @param $type string
     * @return bool
     * @throws \Exception
     */
    public function log($row , $type = ""){
        $model = new SetWorkspacesRunningLog();
        $model->qq_id = $row->id;
        $model->type = $type.$this->isRunning($row)."|".$row->zt;
        $model->save();
    }

    /**
     * @param $row SetWorkspacesSjqq
     * @return bool
     * @throws \Exception
     */
    public function curl($row){
        if($this->isRunning($row)){
            return false;
        }
        $this->setRunning($row,true);
        $this->running($row);
        $this->log($row,"提交到三方API");
        $this->setJson($row->url);
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->apiEndPoint,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $this->json,
            CURLOPT_HTTPHEADER => array(
                $this->getAuth(),
                "Content-Type: application/json"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);
        $this->setRunning($row,false);
        if($err){
            $row->zt = SetWorkspacesSjqq_ztEnum::FAIL;
            $row->err_msg = $err;
            $row->save();
            return false;
        }else{
            $data = Json::decode($response);
            $response_id = ArrayHelper::getValue($data,"responseId");
            if($response_id){
                $row->zt = SetWorkspacesSjqq_ztEnum::RESPONSE_UNDO;
                $row->response_id = ArrayHelper::getValue($data,"responseId");
                $row->save();
            }else{
                $row->err_msg = $response;
                $row->zt = SetWorkspacesSjqq_ztEnum::FAIL;
                $row->save();
                return false;
            }

            return true;
        }
    }

    /**
     * @param $row SetWorkspacesSjqq
     * @return bool
     * @throws \Exception
     */
    public function curlRes($row){
        if(empty($row->response_id)){
            return false;
        }
        if($this->isRunning($row)){
            return false;
        }
        $this->setRunning($row,true);
        $this->running($row);
        $this->log($row,"查询三方API");
        $curl = curl_init();

        $url = "http://api.scraping-bot.io/scrape/data-scraper-response?scraper=tiktokProfile&responseId={$row->response_id}";

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_HTTPGET => true,
            CURLOPT_HTTPHEADER => array(
                $this->getAuth(),
                "Content-Type: application/json"
            ),
        ));

        // 执行 cURL 请求并获取返回结果
        $response = curl_exec($curl);
        // 检查是否有错误发生
        $err = curl_errno($curl);
        // 关闭 cURL 句柄
        curl_close($curl);
        $this->setRunning($row,false);
        if($err){
            $row->zt = SetWorkspacesSjqq_ztEnum::FAIL_RES;
            $row->err_msg = $err;
            $row->save();
            return false;
        }else{
            if(preg_match('/\"status\"\:\"pending\"/',$response)){
                //采集未完成跳过
                return false;
            }
            if(preg_match('/\"error\"/',$response)){
                $row->zt = SetWorkspacesSjqq_ztEnum::FAIL_RES;
                $row->err_msg = $err;
                $row->save();
                return false;
            }
            $row->zt = SetWorkspacesSjqq_ztEnum::RESPONSE_WAIT_ANALYSIS;
            $row->save();

            $sj_model = $row['sjdl'];
            if(empty($sj_model)){
                $sj_model = new SetWorkspacesSjdl();
                $sj_model->id = $row->id;
            }

            $sj_model->res = base64_encode($response);
            $sj_model->save();
            return true;
        }
    }

    public function createResponse($url){
        if(SetWorkspacesSjqq::find()->andWhere(['url' => $url])->exists()){
            return false;
        }
        $model = new SetWorkspacesSjqq();
        $model->url = $url;
        $model->zt = SetWorkspacesSjqq_ztEnum::UNDO;
        return $model->save();
    }

    /**
     * @param $row SetWorkspacesSjqq
     * @return bool
     * @throws \Exception
     */
    public function analysis($row){
        if($this->isRunning($row)){
            return false;
        }
        $this->setRunning($row,true);
        /**
         * @var $sj_model SetWorkspacesSjdl
         */
        $sj_model = $row['sjdl'];
        if(empty($sj_model)){
            throw new Exception("{$row->id}不存在数据");
        }
        $this->running($row);
        $this->log($row,"解析数据结果");
        $str = base64_decode($sj_model->res);
        $json = Json::decode($str,true);
        $item = ArrayHelper::getValue($json,"0");
        if($item){
            $sj_model->influencer_id = ArrayHelper::getValue($item,'influencer_id');
            $sj_model->biography = base64_encode(ArrayHelper::getValue($item,'biography'));
            $sj_model->bio_link = ArrayHelper::getValue($item,'bio_link');
            $sj_model->nickname = base64_encode(ArrayHelper::getValue($item,'nickname'));
            $sj_model->avatar = ArrayHelper::getValue($item,'avatar');
            $sj_model->followers = ArrayHelper::getValue($item,'followers');
            $sj_model->hearts = ArrayHelper::getValue($item,'hearts');
            $sj_model->videos_count = ArrayHelper::getValue($item,'videos_count');
            $sj_model->responseid = $row->response_id;
            $sj_model->following =  ArrayHelper::getValue($item,'following');
            $sj_model->email =  $this->getEmail($sj_model->biography);
            if($sj_model->save()){
                $row->zt = SetWorkspacesSjqq_ztEnum::SUCCESS;
                $row->save();
            }
//            $top_videos = ArrayHelper::getValue($item,'top_videos');
//            if($top_videos){
//                $top_videos = array_map(function($item) use ($row){
//                    return [
//                        'tk_id' => ArrayHelper::getValue($item,'id'),
//                        'description'=> base64_encode(ArrayHelper::getValue($item,'description','')),
//                        'create_time'=> ArrayHelper::getValue($item,'create_time','0'),
//                        'collect_count'=> ArrayHelper::getValue($item,'collect_count','0'),
//                        'comment_count'=> ArrayHelper::getValue($item,'comment_count','0'),
//                        'digg_count'=> ArrayHelper::getValue($item,'diggCount','0'),
//                        'play_count'=> ArrayHelper::getValue($item,'playCount','0'),
//                        'share_count'=> ArrayHelper::getValue($item,'shareCount','0'),
//                        'thumbnail'=> ArrayHelper::getValue($item,'thumbnail',''),
//                        'display_url'=> ArrayHelper::getValue($item,'display_url',''),
//                        'video'=> base64_encode(Json::encode(ArrayHelper::getValue($item,'video'))),
//                        'music'=> base64_encode(Json::encode(ArrayHelper::getValue($item,'music'))),
//                        'sjfx_id'=> $row->id,
//                    ];
//                },$top_videos);
//
//                $num = \Yii::$app->db->createCommand()->batchInsert(SetWorkspacesYhsp::tableName(),array_keys($top_videos[0]),$top_videos)->execute();
//
//                var_dump($num);
//            }
        }

        $this->setRunning($row,false);
    }

    public function getEmail($str){
        $pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/';
        if(preg_match($pattern,$str,$out)){
            return $out[1];
        }
        return "";
    }
}